import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:flutter/material.dart';
import '../../../utils/photo_utils/photo_tool.dart';
import 'company_profile_controller.dart';
import 'package:get/get.dart';
import 'dart:io';
import 'package:dio/dio.dart' as dioFile;
import '../../../utils/loading.dart';
import 'package:fate_blind_box/network/http_request.dart';

//编辑企业简介
class CompanyProfileView extends StatefulWidget {
  Map<String, dynamic>? resMap;
  Function? refreshBlock;
  bool isFromUpload = false;
  Function? callBackBlock;

  CompanyProfileView(
      {Key? key,
      this.resMap,
      this.refreshBlock,
      this.isFromUpload = false,
      this.callBackBlock})
      : super(key: key);

  @override
  State<CompanyProfileView> createState() => _CompanyProfileState();
}

class _CompanyProfileState extends State<CompanyProfileView> {
  final TextEditingController _nameController = TextEditingController();
  CompanyProfileController companyProfileController =
      Get.put(CompanyProfileController());

  @override
  void initState() {
    super.initState();
    if (widget.resMap != null) {
      if (widget.resMap?['introduce'] != null) {
        _nameController.text = widget.resMap?['introduce'];
      }
      if (widget.resMap?['matchPhoto'] != null) {
        companyProfileController.photoCoverUrl = widget.resMap?['matchPhoto'];
      }
      if (widget.resMap?['matchProducts'] != null) {
        companyProfileController.photoDetailsUrl =
            widget.resMap?['matchProducts'];
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return AppWidget.navTitleBar(
        title: '编辑商家简介',
        rightActions: [
          Container(
            margin: const EdgeInsets.only(right: 15, top: 10, bottom: 10),
            height: 31,
            child: TextButton(
              style: TextButton.styleFrom(
                backgroundColor: ThemeColor.appColor,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(5)),
                textStyle: const TextStyle(color: Colors.white),
              ),
              child: const Text(
                '完成',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                saveBtnAction();
              },
            ),
          )
        ],
        childWidget: SingleChildScrollView(
          child: Container(
              margin: const EdgeInsets.fromLTRB(15, 14, 15, 0),
              child: Column(
                children: [
                  GetBuilder(
                      id: companyProfileController.photoCoverId,
                      builder: (CompanyProfileController controller) {
                        ImageProvider imageProvider;
                        if (controller.photoCoverUrl.contains('http')) {
                          imageProvider =
                              NetworkImage(controller.photoCoverUrl);
                        } else {
                          imageProvider =
                              FileImage(File(controller.photoCoverUrl));
                        }

                        return GestureDetector(
                          onTap: () {
                            //图片点击事件
                            _selectPhoto(context, size.width, isCover: true);
                          },
                          child: Container(
                              height: 335,
                              width: size.width - 40,
                              alignment: Alignment.center,
                              decoration: controller.photoCoverUrl.isNotEmpty
                                  ? BoxDecoration(
                                      color: Colors.white,
                                      image: DecorationImage(
                                        fit: BoxFit.cover,
                                        image: imageProvider,
                                      ),
                                    )
                                  : BoxDecoration(color: Colors.white),
                              child: Visibility(
                                visible: controller.photoCoverUrl.isEmpty,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Image.asset(
                                      "images/ic_qiyeminiPhoto.png",
                                      width: 37,
                                      height: 31,
                                      fit: BoxFit.cover,
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    const Text(
                                      '+添加企业图片',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 16,
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    const Text(
                                      '高颜值的图片能帮助您获得更多的曝光',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 14,
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    const Text(
                                      '建议宽高比例为1：1',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 14,
                                      ),
                                    ),
                                  ],
                                ),
                              )),
                        );
                      }),
                  const SizedBox(
                    height: 14,
                  ),
                  Container(
                      alignment: Alignment.centerLeft,
                      child: const Text(
                        '七天内可修改三次简介',
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 16,
                        ),
                      )),
                  Container(
                    margin: const EdgeInsets.fromLTRB(0, 14, 0, 0),
                    height: 200,
                    color: Colors.white,
                    child: TextField(
                      maxLength: 100,
                      maxLines: 5,
                      minLines: 5,
                      controller: _nameController,
                      obscureText: false,
                      keyboardType: TextInputType.text,
                      cursorColor: ThemeColor.sendMsgTextColor,
                      style:
                          TextStyle(fontSize: 16, color: ThemeColor.textColor),
                      decoration: InputDecoration(
                        hintText: "点击填写商家简介",
                        border: InputBorder.none,
                        hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: const EdgeInsets.all(20),
                      ),
                    ),
                  ),
                  const SizedBox(
                    height: 10,
                  ),
                  Container(
                      alignment: Alignment.centerLeft,
                      child: const Text(
                        '商家详情图片',
                        style: TextStyle(
                          color: Colors.grey,
                          fontSize: 16,
                        ),
                      )),
                  const SizedBox(
                    height: 10,
                  ),
                  GetBuilder(
                      id: companyProfileController.photoDetailsId,
                      builder: (CompanyProfileController controller) {
                        ImageProvider imageProvider;
                        if (controller.photoDetailsUrl.contains('http')) {
                          imageProvider =
                              NetworkImage(controller.photoDetailsUrl);
                        } else {
                          imageProvider =
                              FileImage(File(controller.photoDetailsUrl));
                        }

                        return GestureDetector(
                          onTap: () {
                            //图片点击事件
                            _selectPhoto(context, size.width, isCover: false);
                          },
                          child: Container(
                              height: 335,
                              width: size.width - 40,
                              alignment: Alignment.center,
                              decoration: controller.photoDetailsUrl.isNotEmpty
                                  ? BoxDecoration(
                                      color: Colors.white,
                                      image: DecorationImage(
                                        fit: BoxFit.cover,
                                        image: imageProvider,
                                      ),
                                    )
                                  : const BoxDecoration(
                                      color: Colors.white,
                                    ),
                              child: Visibility(
                                visible: controller.photoDetailsUrl.isEmpty,
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Image.asset(
                                      "images/ic_qiyeminiPhoto.png",
                                      width: 37,
                                      height: 31,
                                      fit: BoxFit.cover,
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    const Text(
                                      '+添加商家详情图片',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 16,
                                      ),
                                    ),
                                    const SizedBox(
                                      height: 5,
                                    ),
                                    const Text(
                                      '高颜值的图片能帮助您获得更多的曝光',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 14,
                                      ),
                                    ),
                                  ],
                                ),
                              )),
                        );
                      }),
                  const SizedBox(
                    height: 30,
                  ),
                ],
              )),
        ));
  }

  Future<void> _selectPhoto(context, double width,
      {bool isCover = true}) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
            height: 220.0,
            child: Container(
                alignment: Alignment.center,
                child: Column(
                  children: [
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          PhotoTool.getPhotoImgFile('拍照', context,
                              callBack: (url) {
                            choseCoverAndDetails(isCover, url);
                          }, isNoNeedCrop: true);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 55,
                          color: Colors.white,
                          child: const Text('拍照'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      height: 1,
                    ),
                    GestureDetector(
                        onTap: () {
                          Navigator.pop(context);
                          PhotoTool.getPhotoImgFile('相册', context,
                              callBack: (url) {
                            choseCoverAndDetails(isCover, url);
                          }, isNoNeedCrop: true);
                        },
                        child: Container(
                          alignment: Alignment.center,
                          width: width,
                          height: 60,
                          color: Colors.white,
                          child: const Text('从手机相册选择'),
                        )),
                    Divider(
                      color: ThemeColor.sendMsgColor,
                      thickness: 7,
                      height: 1,
                    ),
                    GestureDetector(
                      onTap: () {
                        Navigator.pop(context);
                      },
                      child: Container(
                        alignment: Alignment.center,
                        width: width,
                        height: 55,
                        child: const Text('取消'),
                      ),
                    ),
                  ],
                )));
      },
    );
  }

  //选择封面或者详情
  choseCoverAndDetails(bool isCover, String url) {
    if (isCover) {
      companyProfileController.photoCoverUrl = url;
      companyProfileController.update([companyProfileController.photoCoverId]);
    } else {
      companyProfileController.photoDetailsUrl = url;
      companyProfileController
          .update([companyProfileController.photoDetailsId]);
    }
  }

  saveBtnAction() async {
    if (companyProfileController.photoCoverUrl.isEmpty) {
      toast('请上传图片');
      return;
    }
    if (_nameController.text.isEmpty) {
      toast('请填写简介');
      return;
    }

    Map<String, dynamic> dataMap = {
      // "memberId": Provider.memberId,
      'introd': _nameController.text
    };
    if (companyProfileController.photoCoverUrl.startsWith('http') == false) {
      dataMap['brief'] = dioFile.MultipartFile.fromFileSync(
          companyProfileController.photoCoverUrl);
    } else {
      dataMap['partFile'] = companyProfileController.photoCoverUrl;
    }

    if (companyProfileController.photoDetailsUrl.isNotEmpty) {
      if (companyProfileController.photoDetailsUrl.startsWith('http') ==
          false) {
        dataMap['prodFiles'] = dioFile.MultipartFile.fromFileSync(
            companyProfileController.photoDetailsUrl);
      } else {
        dataMap['prodFile'] = companyProfileController.photoDetailsUrl;
      }
    }

    if (widget.isFromUpload) {
      widget.callBackBlock!(companyProfileController.photoCoverUrl,
          _nameController.text, companyProfileController.photoDetailsUrl);
      Get.back();
    } else {
      final res = await HttpRequest.uploadFile(
          'match-maker/business/uploadBrief',
          params: dataMap);
      if (res['code'] == 0) {
        final data = res['data'];
        if (data != null) {
          toast('保存成功');
          if (widget.refreshBlock != null) {
            widget.refreshBlock!();
          }
          Get.back();
        } else {
          toast(res['msg']);
        }
      } else {
        toast(res['msg']);
      }
    }
  }
}
